﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Drawing;
using System.IO;
using CommonLibCore;
using CustomMVCCore;
using Microsoft.AspNetCore.Mvc;
using NetCoreWeb.Models;
using DbLib;
using DbLib.models;
using NetCoreWeb.Models;
using BLL;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;

namespace NetCoreWeb.Controllers
{
    public class HomeController : Controller
    {
        private readonly order02Context _db;
        private IHttpContextAccessor _accessor;

        private AppParam _appSettings;

        private UserBll userBll = new UserBll();

        public HomeController(order02Context context, IHttpContextAccessor accessor, IOptionsMonitor<AppParam> appSettings)
        {
            _db = context;
            _accessor = accessor;
            _appSettings = appSettings.CurrentValue; //IOptions 需要每次重新启动项目加载配置，IOptionsMonitor 每次更改配置都会重新加载，不需要重新启动项目。

        }

        public IActionResult Login()
        {
            return View();
        }

        public IActionResult Captcha()
        {
            ADSSAntiBot captcha = new ADSSAntiBot();
            string str = captcha.DrawNumbers(5);            
            var httpConetext = _accessor.HttpContext;
            
            
            httpConetext.Session.SetString(ADSSAntiBot.SESSION_CAPTCHA, str);
            
          
            Bitmap bmp = captcha.Result;
            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return File(ms.ToArray(), "image/jpeg");
        }

        [HttpPost, OpLog("用户登录"), ErrorOper]
        public JsonResult LoginOper(string loginName, string loginPassword, string captcha)
        {
            var httpConetext = _accessor.HttpContext;
            var aaa = httpConetext.Session.GetString("CAPTCHA");
            if (httpConetext.Session.GetString("CAPTCHA") == captcha)
            {
                Trace.WriteLine(DateTime.Now + "用户名：" + loginName + "尝试登陆" + "\n\r");
                PreUser user = new PreUser
                {
                    Username = loginName,
                    Password = GeneralTools.MD5Encrpyt(_appSettings.PassSalt + loginPassword),
                    Logip = httpConetext.Request.Host.Host
                };

                PreUser list = userBll.Login(user);
                if (!Equals(list, null))
                {
                    if (list.Islive == 1)
                    {
                        List<PreUser> loginUser = WebVar<PreUser>.GetList;
                        loginUser.Add(list);
                        Trace.WriteLine(DateTime.Now + "用户名：" + loginName + "登陆成功" + "\n\r");

                        return this.Json(new RequestResult { Result = "OK", Message = "/Main/" });
                    }
                    else
                    {
                        Trace.WriteLine(DateTime.Now + "用户名：" + loginName + "尚未激活" + "\n\r");

                        return this.Json(new RequestResult { Result = "Fail", Message = "用户：" + loginName + "尚未激活" });
                    }
                }
                else
                {
                    Trace.WriteLine(DateTime.Now + "用户名：" + loginName + "登陆失败，用户名或密码不正确！");
                    return this.Json(new RequestResult { Result = "Fail", Message = "用户名或密码不正确！" });
                }
            }
            else
            {
                Trace.WriteLine("用户名：" + loginName + "登陆失败，验证码不正确！");
                return this.Json(new RequestResult { Result = "Fail", Message = "验证码不正确！" });
            }

        }

        public IActionResult Index()
        {
            try
            {
                var query = _db.PreUser.AsQueryable();
                List<PreUser> users = LinqHelperExtension.Where(query, new Conditioner[] { }).ToList();
            }
            catch (Exception ex)
            {

            }
            return View();
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
